﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using SmartSiteManagementSystem.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Authorization;
using System.IdentityModel.Tokens.Jwt;
using SmartSiteManagementSystem.Services.Jwt;
using System.Collections;
using SmartSiteManagementSystem.Models.User;
using SmartSiteManagementSystem.Models.DTO;
using SmartSiteManagementSystem.Models.Enums;
using SmartSiteManagementSystem.Utils;
using SmartSiteManagementSystem.AppApi.RequestBodyInputParamDto;
using SmartSiteManagementSystem.AppApi.Common;
using SmartSiteManagementSystem.AppApi.ResponseBodyOutputParamDto;

namespace SmartSiteManagementSystem.AppApi.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ApiBaseController
    {
        private readonly IUserService _userService;
        private readonly IHttpContextAccessor _httpContext;
        private readonly IJWTService _iJWTService;

        /// <summary>
        /// 
        /// </summary>
        public UserController(IUserService userService, IHttpContextAccessor httpContext, IJWTService iJWTService)
        {
            _userService = userService;
            _httpContext = httpContext;
            _iJWTService = iJWTService;
        }

        /// <summary>
        /// 登录接口API
        /// </summary>
        /// <param name="userLoginRequestBodyParamDto">请求内容 {"loginName":"xxx","loginPwd":"sssss"}</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("Login")]
        public IActionResult Login([FromBody] UserLoginRequestBodyParamDto userLoginRequestBodyParamDto)
        {
            SSMSApiResult<Hashtable> reslut = new SSMSApiResult<Hashtable>();
            reslut.Code = StateCodeEnum.Fail;
            reslut.Data = new Hashtable();
            reslut.Msg = "操作失败";
            ApiRequestCustomHeadInfo apiRequestCustomHeadInfo = RequestHeadHelper.GetApiRequestCustomHeadInfo(_httpContext.HttpContext);
            try
            {
                if (string.IsNullOrEmpty(userLoginRequestBodyParamDto.LoginName) || string.IsNullOrEmpty(userLoginRequestBodyParamDto.LoginPwd))
                {
                    #region 提交数据为空
                    reslut.Code = StateCodeEnum.LackSubmitParam;
                    reslut.Msg = "登录名和密码不能为空";
                    #endregion
                }
                else
                {
                    #region 主要业务

                     UserInfo userInfo =  _userService.GetUserInfoByLogin(userLoginRequestBodyParamDto.LoginName);
                    if (userInfo != null)
                    {

                        #region 用户存在
                        string encryptLoginPwd = EncryptionUtils.GetUserLoginPwd_SHA1(userLoginRequestBodyParamDto.LoginName, userLoginRequestBodyParamDto.LoginPwd);
                        if(encryptLoginPwd== userInfo.LogonPwd)
                        {
                            string token = _iJWTService.GetToken(userInfo.LogonName);
                            Hashtable param = new Hashtable();
                            #region 密码正确
                            reslut.Code = StateCodeEnum.Ok;
                            reslut.Msg = "登录成功!";
                            param.Add("asessToken", token);
                            param.Add("userId", userInfo.UserId);
                            param.Add("auth", EncryptionUtils.GetUserLoginAuth_SHA1(userInfo.LogonName, userInfo.LogonPwd));
                            reslut.Data = param;
                            #region 更新用户登录信息
                            userInfo.LoginCount = userInfo.LoginCount + 1;
                            userInfo.LastestLogonTime = DateTime.Now;
                            userInfo.LastestLogonIp = IPUtils.GetIPRealAddress(HttpContext);
                            _userService.UpdateUserInfo(userInfo);
                            #endregion
                            #endregion
                        }
                        else
                        {
                            #region 密码不正确
                            reslut.Code = StateCodeEnum.Fail;
                            reslut.Msg = "密码不正确!";
                            #endregion

                        }
                        #endregion
                    }
                    else
                    {
                        #region 用户不存在
                        reslut.Code = StateCodeEnum.Fail;
                        reslut.Msg = "账号不存在";
                        #endregion
                    }
                    
                    #endregion
                }
            }
            catch(Exception e)
            {
                reslut.Code = StateCodeEnum.InternalServerError;
                reslut.Msg = "服务器错误";

            }
            return Ok(reslut);
        }



        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userIdTokenRequestBodyParamDto"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost, Route("GetUserInfo")]
        public IActionResult GetUserInfo([FromBody] UserIdTokenRequestBodyParamDto userIdTokenRequestBodyParamDto)
        {
            SSMSApiResult<Hashtable> reslut = new SSMSApiResult<Hashtable>();
            reslut.Code = StateCodeEnum.Fail;
            reslut.Data = new Hashtable();
            reslut.Msg = "操作失败";
            ApiRequestCustomHeadInfo apiRequestCustomHeadInfo = RequestHeadHelper.GetApiRequestCustomHeadInfo(_httpContext.HttpContext);
            try
            {
                if (string.IsNullOrEmpty(userIdTokenRequestBodyParamDto.Auth) || userIdTokenRequestBodyParamDto.UserId==0)
                {
                    #region 提交数据为空
                    reslut.Code = StateCodeEnum.LackSubmitParam;
                    reslut.Msg = "提交参数不能为空";
                    #endregion
                }
                else
                {
                    #region 主要业务

                    UserInfo userInfo = _userService.GetUserInfoById(userIdTokenRequestBodyParamDto.UserId);

                    if (userInfo != null)
                    {

                        #region 用户存在
                        string encryptAuth = EncryptionUtils.GetUserLoginAuth_SHA1(userInfo.LogonName, userInfo.LogonPwd);
                        if (encryptAuth == userIdTokenRequestBodyParamDto.Auth)
                        {
                            GetUserInfoResponseBodyParamDto getUserInfoResponseBodyParamDto = new GetUserInfoResponseBodyParamDto{
                                 LogonName=userInfo.LogonName,
                                 LastestLogonTime=userInfo.LastestLogonTime,
                                 UserId=userInfo.UserId,
                                 Email=userInfo.Email,
                                 HeadPic=userInfo.HeadPic,
                                 Mobile=userInfo.Mobile,
                                 Sex=userInfo.Sex,
                                 PositionType=userInfo.PositionType,
                                 RegTypeName=userInfo.PositionTypeName,
                                 ShowName=userInfo.ShowName
                            };
                            Hashtable useinfoHashtable = new Hashtable();
                            useinfoHashtable.Add("userInfo", getUserInfoResponseBodyParamDto);
                            #region 密码正确
                            reslut.Code = StateCodeEnum.Ok;
                            reslut.Msg = "操作成功!";
                            reslut.Data = useinfoHashtable;
                            #endregion
                        }
                        else
                        {
                            #region 密码不正确
                            reslut.Code = StateCodeEnum.Fail;
                            reslut.Msg = "密码不正确!";
                            #endregion

                        }
                        #endregion
                    }
                    else
                    {
                        #region 用户不存在
                        reslut.Code = StateCodeEnum.Fail;
                        reslut.Msg = "账号不存在";
                        #endregion
                    }

                    #endregion
                }
            }
            catch (Exception e)
            {
                reslut.Code = StateCodeEnum.InternalServerError;
                reslut.Msg = "服务器错误";

            }
            return Ok(reslut);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="userIdTokenRequestBodyParamDto"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost, Route("UserLayout")]
        public IActionResult UserLayout([FromBody] UserIdTokenRequestBodyParamDto userIdTokenRequestBodyParamDto)
        {
            ApiRequestCustomHeadInfo apiRequestCustomHeadInfo = RequestHeadHelper.GetApiRequestCustomHeadInfo(_httpContext.HttpContext);
            SSMSApiResult<Hashtable> reslut = new SSMSApiResult<Hashtable>();
            reslut.Code = StateCodeEnum.Ok;
            reslut.Data = new Hashtable();
            reslut.Msg = "操作成功";
            return Ok(reslut);
        }
        

    }
}
